package larpplanner.gui;

import larpplanner.database.Quest;
import larpplanner.logic.QuestSummary;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import com.cloudgarden.resource.SWTResourceManager;

public class QuestSelectionWin extends org.eclipse.swt.widgets.Composite {

    private GUISafeLARPManager mngr = GUISafeLARPManager.get();
	
	private java.util.List<QuestSummary> quests;
    
    private Long userID; // TODO: use this
    
    private Button addBtn;
    private Button rmvBtn;
    private Button logoutBtn;
    private Group grp;
    private Label imgLbl;
    private List questLst;
    private Label lbl;
    private Composite btnHome;

    {
        //Register as a resource user - SWTResourceManager will
        //handle the obtaining and disposing of resources
        SWTResourceManager.registerResourceUser(this);
    }

    public QuestSelectionWin(Composite parent, int style, long userID) {
        super(parent, style);
        this.userID = userID;
        initGUI();
        initLogic();
    }
    
    private void initLogic() {
        
    	mngr.getQuests(new SafeCallback<java.util.List<QuestSummary>>() {
    		public void onReturn(java.util.List<QuestSummary> questSummaryList) {
    			quests = questSummaryList;
    			for(QuestSummary q : quests)
    	    		questLst.add(q.getName()+" ("+q.getNumOfParticipants()+" players)");
    		}
    	});
    	
    	rmvBtn.setEnabled(false);
        rmvBtn.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent event) {
            	// open window "are you sure?"
                MessageBox mb = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
                mb.setText("Confirm delete");
                mb.setMessage("Are you sure you want to delete this quest?");
                int buttonID = mb.open();
                if(buttonID == SWT.YES){
                	int selectionIndex = questLst.getSelectionIndex();
                	mngr.del(Quest.class, quests.get(selectionIndex).getId(), new SafeCallback<Boolean>() {
						public void onReturn(Boolean result) {
							if(!result)
								PopMessage.errorMessage("quest delete failed");
						}
                	});
                	quests.remove(selectionIndex);
                    questLst.remove(selectionIndex);
                    rmvBtn.setEnabled(false);
                }
            }
        });  
        
    	questLst.addSelectionListener(new SelectionAdapter() {
			// single click on quest in list - enable remove button
    		public void widgetSelected(SelectionEvent e) {
				rmvBtn.setEnabled(true);
			}
			
    		// double click on quest in list - edit that quest
			public void widgetDefaultSelected(SelectionEvent e) {
				final int idx = questLst.getSelectionIndex();
				if(idx == -1)
					return;
				QuestSummary editQuestSummary = quests.get(idx);
				mngr.get(Quest.class, editQuestSummary.getId(), new SafeCallback<Quest>() {
					public void onReturn(Quest editQuest) {
						if(editQuest == null)
							PopMessage.errorMessage("error fetching the selected quest from DB");
						QuestEditDialog dialog = new QuestEditDialog(getShell(), SWT.NONE, editQuest);
						dialog.open();
						questLst.setItem(idx, dialog.getQuestName()+" ("+dialog.getQuestSize()+" players)");
					}
				});
			}
		});
        
        // adding a new quest
        addBtn.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                final QuestEditDialog dialog;
                dialog = new QuestEditDialog(getShell(), SWT.NONE, null);
                Quest newQuest = dialog.open();
                //TODO: add the new quest to the quest list
                if(newQuest != null){
                	mngr.summaryFromQuest(newQuest, new SafeCallback<QuestSummary>() {
                		public void onReturn(QuestSummary newQuestSummary) {
                			questLst.add(dialog.getQuestName()+" ("+dialog.getQuestSize()+" players)");
                        	quests.add(newQuestSummary);
                		}
                	});
                }
            }
        });
        
        // logging out
        logoutBtn.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
            	getShell().dispose();
            	LoginWin.openLoginWin();
            }
        });
    }

    private void initGUI() {
        try {
            this.setSize(600, 269);
            GridLayout thisLayout = new GridLayout();
            thisLayout.numColumns = 2;
            this.setLayout(thisLayout);
            this.setBackground(SWTResourceManager.getColor(241, 211, 171));
            {
                GridData imgLblLData = new GridData();
                imgLblLData.grabExcessVerticalSpace = true;
                imgLblLData.verticalSpan = 3;
                imgLbl = new Label(this, SWT.NONE);
                imgLbl.setLayoutData(imgLblLData);
                imgLbl.setImage(SWTResourceManager.getImage("img/helm02s.jpg"));
            }
            {
                lbl = new Label(this, SWT.NO_BACKGROUND);
                GridData lblLData = new GridData();
                lblLData.horizontalIndent = 5;
                lbl.setLayoutData(lblLData);
                lbl.setText("Select existing quest or create a new one");
                lbl.setFont(SWTResourceManager.getFont("Lucida Calligraphy", 14, 0, false, false));
                lbl.setBackground(SWTResourceManager.getColor(241, 211, 171));
            }
            {
                GridData grpData = new GridData();
                grpData.grabExcessHorizontalSpace = true;
                grpData.heightHint = SWT.END;
                grpData.widthHint = SWT.END;
                grpData.grabExcessVerticalSpace = true;
                grp = new Group(this, SWT.NO_BACKGROUND);
                FillLayout grpLayout = new FillLayout(org.eclipse.swt.SWT.HORIZONTAL);
                grp.setLayout(grpLayout);
                grp.setLayoutData(grpData);
            }
            {
                questLst = new List(grp, SWT.NONE);
                questLst.setDragDetect(false);
                questLst.setFont(SWTResourceManager.getFont("Segoe UI", 11, 0, false, false));
                questLst.setBackground(SWTResourceManager.getColor(250, 238, 222));
                questLst.setToolTipText("double click a quest to edit it");
            }
            {
                btnHome = new Composite(this, SWT.NONE);
                RowLayout btnHomeLayout = new RowLayout(org.eclipse.swt.SWT.HORIZONTAL);
                btnHomeLayout.marginTop = 0;
                GridData btnHomeLData = new GridData();
                btnHomeLData.grabExcessHorizontalSpace = true;
                btnHome.setLayoutData(btnHomeLData);
                btnHome.setLayout(btnHomeLayout);
                btnHome.setBackground(SWTResourceManager.getColor(241, 211, 171));
            }
            {
                addBtn = new Button(btnHome, SWT.PUSH | SWT.CENTER);
                RowData addBtnLData = new RowData();
                addBtnLData.width = 99;
                addBtn.setLayoutData(addBtnLData);
                addBtn.setText("New Quest");
            }
            {
            	rmvBtn = new Button(btnHome, SWT.PUSH | SWT.CENTER);
            	RowData rmvBtnLData = new RowData();
            	rmvBtnLData.width = 81;
            	rmvBtn.setLayoutData(rmvBtnLData);
            	rmvBtn.setText("Delete");
            }
            {
            	logoutBtn = new Button(btnHome, SWT.PUSH | SWT.CENTER);
            	RowData logoutBtnLData = new RowData();
            	logoutBtnLData.width = 81;
            	logoutBtn.setLayoutData(logoutBtnLData);
            	logoutBtn.setText("Logout");
            }
            this.layout();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void open() {
    	Shell shell = getShell();
    	Point size = getSize();
        shell.setLayout(new FillLayout());
        shell.setText("LARP Planner");
        shell.layout();
        if(size.x == 0 && size.y == 0) {
            pack();
            shell.pack();
        } else {
            Rectangle shellBounds = shell.computeTrim(0, 0, size.x, size.y);
            shell.setSize(shellBounds.width, shellBounds.height);
        }
        shell.open();
        Display display = shell.getDisplay();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
    }
    
    public static void main(String[] args) {
        Display display = Display.getDefault();
        Shell shell = new Shell(display);
        QuestSelectionWin inst = new QuestSelectionWin(shell, SWT.NULL,1);
        inst.open();
    }

}
